import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class WeappAuthService extends BaseService<any> {
  private readonly logger = new Logger(WeappAuthService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getUserInfoByCode
   * 对应 PHP: WeappAuthService_api::getUserInfoByCode()
   * 逻辑类型: undefined - undefined
   */
  async getUserInfoByCode(code: string) {
    // 基于PHP真实逻辑: getUserInfoByCode
    // PHP原文: //        $iv = $this->request->param('iv', ''); //        $encrypted_data = $this->request->param('encrypted_data', '');         $result = $this->cor...
//        iv = this.request.param('iv', ''];
//        encrypted_data = this.request.param('encrypted_data', ''];
        const result = this.core_weapp_serve_service.session(this.site_id, code);
//        if(!result)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
//        userinfo = this.core_weapp_serve_service.decryptData(result.session_key, iv, encrypted_data];
        const openid = result[ 'openid' ] || '';//对应微信的 openid
        const unionid = result[ 'unionid' ) || '';//对应微信的 unionid
        if (!openid)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
        //todo 这儿还可能会获取用户昵称 头像  性别 ....用以更新会员信息
//        nickname = userinfo.nickName || '';//对应微信的 nickname
//        avatar = userinfo.avatarUrl || '';//对应微信的 头像地址
//        sex = userinfo.gender;//性别
        return [
            openid,
            unionid,
//            avatar,
//            nickname,
//            sex
        );
    }

    /**
     * 登录
     * @param data
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws InvalidConfigBusinessException
     * @throws ModelNotFoundBusinessException
     * @throws \EasyWeChat\Kernel\BusinessExceptions\InvalidArgumentBusinessException
     * @throws \Symfony\Contracts\HttpClient\BusinessException\TransportBusinessExceptionInterface
     */
    async login(data)
    {

        [
            openid,
            unionid,
//            avatar,
//            nickname,
//            sex
        ] = this.getUserInfoByCode(data[ 'code' )];

        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ weapp_openid: openid, site_id: this.site_id )];
        if (member_info.isEmpty() && !!unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) {
                member_info.weapp_openid = openid;
            }
  }

  /**
   * login
   * 对应 PHP: WeappAuthService_api::login()
   * 逻辑类型: undefined - undefined
   */
  async login(data: any) {
    // 基于PHP真实逻辑: login
    // PHP原文: [             $openid,             $unionid, //            $avatar, //            $nickname, //            $sex         ] = $this->getUserInfoByCode($...
[
            openid,
            unionid,
//            avatar,
//            nickname,
//            sex
        ] = this.getUserInfoByCode(data[ 'code' )];

        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ weapp_openid: openid, site_id: this.site_id )];
        if (member_info.isEmpty() && !!unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) {
                member_info.weapp_openid = openid;
            }
  }

  /**
   * register
   * 对应 PHP: WeappAuthService_api::register()
   * 逻辑类型: undefined - undefined
   */
  async register(openid: string, mobile: string, mobile_code: string, wx_unionid: string, nickname: string, headimg: string) {
    // 基于PHP真实逻辑: register
    // PHP原文: if (empty($openid)) throw new AuthException('AUTH_LOGIN_TAG_NOT_EXIST');         if (empty($mobile)) {             if (!empty($mobile_code)) {        ...
if (!openid)) throw new AuthBusinessException('AUTH_LOGIN_TAG_NOT_EXIST');
        if (!mobile)) {
            if (!!mobile_code)) {
                const result = this.core_weapp_serve_service.getUserPhoneNumber(this.site_id, mobile_code);
                if (!result)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
                const phone_info = result[ 'phone_info' ];
                const mobile = phone_info[ 'purePhoneNumber' );
                if (!mobile)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST');
            }
            const is_verify_mobile = false;
  }

  /**
   * updateOpenid
   * 对应 PHP: WeappAuthService_api::updateOpenid()
   * 逻辑类型: undefined - undefined
   */
  async updateOpenid(code: string) {
    // 基于PHP真实逻辑: updateOpenid
    // PHP原文: [             $openid,             $unionid, //            $avatar, //            $nickname, //            $sex         ] = $this->getUserInfoByCode($...
[
            openid,
            unionid,
//            avatar,
//            nickname,
//            sex
        ] = this.getUserInfoByCode(code);
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ weapp_openid: openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ weapp_openid: openid )];
        return true;
    }

}
  }
}
